package com.ts.enterprise.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Dean
 * @Date 2021/10/20 11:47
 * @Description
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
        template.setDefaultSerializer(ser);
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }

    /**
     * 自定义缓存时间管理器
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        Set cacheNames = new HashSet<>();
        cacheNames.add("user");
        cacheNames.add("userBasic");
        ConcurrentHashMap configMap = new ConcurrentHashMap<>();
        //有效期6分钟自定义缓存时间
        configMap.put("user", config.entryTtl(Duration.ofHours(96L)));
        configMap.put("userBasic", config.entryTtl(Duration.ofHours(96L)));
        //永久 key1 的有效期是永久的
//        configMap.put("distributor", config);
        //需要先初始化缓存名称，再初始化其它的配置。
        return RedisCacheManager.builder(factory).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();
    }
}
